package com.ls.lserp.modules.produce.web;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.text.ParseException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.ls.lserp.modules.sys.utils.SystemMessageUtils;
import org.apache.commons.collections.map.HashedMap;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.ls.lserp.common.config.Global;
import com.ls.lserp.common.persistence.AjaxDone;
import com.ls.lserp.common.persistence.BaseEntity;
import com.ls.lserp.common.persistence.Page;
import com.ls.lserp.common.utils.ResourcesUtil;
import com.ls.lserp.common.utils.StringUtils;
import com.ls.lserp.common.web.BaseController;
import com.ls.lserp.modules.produce.entity.ProduceNotice;
import com.ls.lserp.modules.produce.entity.ProducePlan;
import com.ls.lserp.modules.produce.service.ProducePlanService;
import com.ls.lserp.modules.purchase.entity.PurchaseAdvance;
import com.ls.lserp.modules.purchase.entity.PurchaseContract;
import com.ls.lserp.modules.purchase.service.PurchaseAdvanceService;
import com.ls.lserp.modules.purchase.service.PurchaseContractService;

import freemarker.template.Configuration;
import groovy.util.ResourceException;

@Controller
@RequestMapping(value = "${adminPath}/produce/plan/")
public class ProducePlanController extends BaseController {


    @Autowired
    private ProducePlanService producePlanService;

    @Autowired
    Configuration freemarkerConfiguration;

    @ModelAttribute
    public ProducePlan get(@RequestParam(required = false) String id) {

        // 判断id是否为空
        if (StringUtils.isNotBlank (id)) {

            // 执行查询语句 查询基本信息
            return producePlanService.findByID (Long.parseLong (id));
        } else {

            // 若为空，实例化
            return new ProducePlan ();
        }
    }

    /**
     * 拼接一览画面
     *
     * @return
     */
    @RequiresPermissions("produce:plan:view")
    @RequestMapping(value = {"searchList",""})
    public String searchList(ProducePlan producePlan,Model model) throws Exception {

        List <ProducePlan> groupList = producePlanService.findGroupList ();
        // 查询一览页面数据
        if(producePlan.getUlSelected()==null) {
            producePlan.setUlSelected("0");
        }
        List <ProducePlan> list = producePlanService.findProducePlanList (producePlan);
        model.addAttribute ("groupList", groupList);
        model.addAttribute ("planList", list);
        model.addAttribute("ognizationName",producePlan.getOgnizationName());
        model.addAttribute("userGroupID",producePlan.getUserGroupID());
        model.addAttribute("dateStart",producePlan.getDateStart());
        model.addAttribute("dateEnd",producePlan.getDateEnd());
        // ajax返回结果
        return "modules/produce/producePlan";
    }


    /**
     * 功能：Java读取txt文件的内容
     * 1：先获得文件句柄
     * 2：获得文件句柄当做是输入一个字节码流，需要对这个输入流进行读取
     * 3：读取到输入流后，需要读取生成字节流
     *
     * @param filePath
     * @return html
     */
    public String readTxtFile(String filePath) {
        String strHtml = "";
        try {
            String encoding = "UTF-8";
            File file = new File (filePath);
            // 判断文件是否存在
            if (file.isFile ()) {
                InputStreamReader read = new InputStreamReader (
                        // 考虑到编码格式
                        new FileInputStream (file), encoding);
                BufferedReader bufferedReader = new BufferedReader (read);
                String lingText = null;
                while ((lingText = bufferedReader.readLine ()) != null) {
                    strHtml += lingText;
                }
                read.close ();
            } else {

            }
        } catch (Exception e) {
            e.printStackTrace ();
        }
        return strHtml;
    }


    /**
     * 创建采购预付款信息窗口
     *
     * @return
     */
    @RequiresPermissions("produce:plan:view")
    @RequestMapping(value = {"createPlan"})
    public String createPlan(ProducePlan producePlan, Model model) {
        List <ProducePlan> groupList = producePlanService.findGroupList ();
        model.addAttribute ("groupList", groupList);
        producePlan.preInsert ();
        model.addAttribute ("producePlan", producePlan);
        return "modules/produce/producePlanCreate";
    }

    /**
     * 查看一条采购预付款信息
     *
     * @return
     */
    @RequiresPermissions("produce:plan:view")
    @RequestMapping(value = {"viewPlan"})
    public String viewPlan(ProducePlan producePlan, Model model) {
        producePlan = producePlanService.getPlan (producePlan);
        List <ProducePlan> groupList = producePlanService.findGroupList ();
        model.addAttribute ("groupList", groupList);
        model.addAttribute ("producePlan", producePlan);
        return "modules/produce/producePlanShow";
    }

    /**
     * 编辑采购预付款信息窗口
     *
     * @return
     */
    @RequiresPermissions("produce:plan:view")
    @RequestMapping(value = {"editPlan"})
    public String editPlan(ProducePlan producePlan, Model model) {
        producePlan = producePlanService.getPlan (producePlan);
        List <ProducePlan> groupList = producePlanService.findGroupList ();
        model.addAttribute ("groupList", groupList);
        model.addAttribute ("producePlan", producePlan);
        return "modules/produce/producePlanCreate";
    }

    /** 
     * 创建生产通知单窗口
     *
     * @return
     */
    @RequiresPermissions("produce:plan:view")
    @RequestMapping(value = {"createNotice"})
    public String createNotice(ProducePlan producePlan, Model model) {
        producePlan = producePlanService.getPlan (producePlan);
        List <ProducePlan> groupList = producePlanService.findGroupList ();
        model.addAttribute ("groupList", groupList);
        model.addAttribute ("producePlan", producePlan);
        return "modules/produce/produceNoticeCreate";
    }

    /**
     * 创建编辑保存仓库信息
     *
     * @return
     * @throws ParseException
     * @throws ResourceException
     */
    @RequiresPermissions("produce:plan:edit")
    @RequestMapping(value = "save")
    @ResponseBody
    public String save(ProducePlan producePlan, HttpServletRequest request, HttpServletResponse response,
                       Model model) throws ResourceException {

        // 判断id是否为null （判断新建或修改）
        if (producePlan.getId () != null) {
            // 编辑数据
            // 判断数据是否删除
            ProducePlan producePlanNew = get (producePlan.getId ().toString ());
            // 判断数据是否删除
            if (producePlanNew == null || BaseEntity.DEL_FLAG_DELETE.equals (producePlanNew.getDeleteFlag ())) {
                // 返回提示信息
                return renderString (response, AjaxDone.error (getText ("warehouse_edit_save_msg_fail")));
            }

            // 排他处理
            if (producePlan.getVersion () == get (producePlan.getId ().toString ()).getVersion ()) {

                // 版本号加1
                producePlan.setVersion (producePlan.getVersion () + 1);
            } else {

                // 返回提示信息
                return renderString (response, AjaxDone.error (getText ("warehouse_edit_save_msg_fail")));
            }
        }


        // 保存数据
        producePlanService.saveProducePlan (producePlan);

        // 保存成功返回提示信息
        return renderString (response, AjaxDone.ok (SystemMessageUtils.getMessageName ("warehouse_edit_save_msg_success")));


    }

    /**
     * 提交生产计划
     *
     * @return
     * @throws ParseException
     * @throws ResourceException
     */
    @RequiresPermissions("produce:plan:edit")
    @RequestMapping(value = "commit")
    @ResponseBody
    public String commit(ProducePlan producePlan, HttpServletRequest request, HttpServletResponse response,
                         Model model) throws ResourceException {

        // 判断id是否为null （判断新建或修改）
        if (producePlan.getId () != null) {
            // 编辑数据
            // 判断数据是否删除
            ProducePlan producePlanNew = get (producePlan.getId ().toString ());
            // 判断数据是否删除
            if (producePlanNew == null || BaseEntity.DEL_FLAG_DELETE.equals (producePlanNew.getDeleteFlag ())) {
                // 返回提示信息
                return renderString (response, AjaxDone.error (getText ("warehouse_edit_save_msg_fail")));
            }

            // 排他处理
            if (producePlan.getVersion () == get (producePlan.getId ().toString ()).getVersion ()) {

                // 版本号加1
                producePlan.setVersion (producePlan.getVersion () + 1);
            } else {

                // 返回提示信息
                return renderString (response, AjaxDone.error (getText ("warehouse_edit_save_msg_fail")));
            }
        }


        // 保存数据
        producePlanService.updateStatus (producePlan);

        // 保存成功返回提示信息
        return renderString (response, AjaxDone.ok (SystemMessageUtils.getMessageName ("warehouse_edit_save_msg_success")));


    }

    /**
     * 删除生产计划
     *
     * @return
     * @throws ParseException
     * @throws ResourceException
     */
    @RequiresPermissions("produce:plan:edit")
    @RequestMapping(value = "delete")
    @ResponseBody
    public String delete(ProducePlan producePlan, HttpServletRequest request, HttpServletResponse response,
                         Model model) throws ResourceException {

        // 判断id是否为null （判断新建或修改）
        if (producePlan.getId () != null) {
            // 编辑数据
            // 判断数据是否删除
            ProducePlan producePlanNew = get (producePlan.getId ().toString ());
            // 判断数据是否删除
            if (producePlanNew == null || BaseEntity.DEL_FLAG_DELETE.equals (producePlanNew.getDeleteFlag ())) {
                // 返回提示信息
                return renderString (response, AjaxDone.error (getText ("warehouse_edit_save_msg_fail")));
            }

            // 排他处理
            if (producePlan.getVersion () == get (producePlan.getId ().toString ()).getVersion ()) {

                // 版本号加1
                producePlan.setVersion (producePlan.getVersion () + 1);
            } else {

                // 返回提示信息
                return renderString (response, AjaxDone.error (getText ("warehouse_edit_save_msg_fail")));
            }
        }
        // 保存数据
        producePlanService.deleteProducePlan (producePlan);
        // 保存成功返回提示信息
        return renderString (response, AjaxDone.ok (SystemMessageUtils.getMessageName ("warehouse_edit_save_msg_success")));

    }
    
    /**
     * 更新完成状态 
     *
     * @return
     * @throws ParseException
     * @throws ResourceException
     */
    @RequiresPermissions("produce:plan:edit")
    @RequestMapping(value = "updateCompleteStatus")
    @ResponseBody
    public String updateCompleteStatus(ProducePlan producePlan, HttpServletRequest request, HttpServletResponse response,
                         Model model) throws ResourceException {

        // 判断id是否为null （判断新建或修改）
        if (producePlan.getId () != null) {
            // 编辑数据
            // 判断数据是否删除
            ProducePlan producePlanNew = get (producePlan.getId ().toString ());
            // 判断数据是否删除
            if (producePlanNew == null || BaseEntity.DEL_FLAG_DELETE.equals (producePlanNew.getDeleteFlag ())) {
                // 返回提示信息
                return renderString (response, AjaxDone.error (getText ("warehouse_edit_save_msg_fail")));
            }

            // 排他处理
            if (producePlan.getVersion () == get (producePlan.getId ().toString ()).getVersion ()) {

                // 版本号加1
                producePlan.setVersion (producePlan.getVersion () + 1);
            } else {

                // 返回提示信息
                return renderString (response, AjaxDone.error (getText ("warehouse_edit_save_msg_fail")));
            }
        }
        // 保存数据
        producePlanService.updateCompleteStatus (producePlan);
        // 保存成功返回提示信息
        return renderString (response, AjaxDone.ok (SystemMessageUtils.getMessageName ("warehouse_edit_save_msg_success")));

    }
}
